import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/general_animation_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'building_index_view_model.dart';
import 'edit_delete_pop_menu_widget.dart';
import 'floor_company_item_widget.dart';

/// 创建楼层中的企业-新
class NewCreateFloorCompanyPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "NewCreateFloorCompanyPage";
  final String floorName;
  final String buildingIndexId;
  final FloorCompanyListBean companyInfo;
  final List<FloorCompanyListBean> floorList;
  const NewCreateFloorCompanyPage(
      {Key key, this.floorName,
        this.buildingIndexId, this.companyInfo, this.floorList}) : super(key:key);

  @override
  _NewCreateFloorCompanyPageState createState() => _NewCreateFloorCompanyPageState();
  static Future<bool> navigatorPush(BuildContext context, String buildingIndexId,
      String floorName,  FloorCompanyListBean companyInfo, List<FloorCompanyListBean> floorList){
    return RouterUtils.routeForFutureResult(
        context,
        NewCreateFloorCompanyPage(
          floorName: floorName,
          buildingIndexId: buildingIndexId,
          companyInfo: companyInfo,
          floorList: floorList,
        ),
        routeName: NewCreateFloorCompanyPage.ROUTER
    );
  }
}

class _NewCreateFloorCompanyPageState
    extends BaseState<NewCreateFloorCompanyPage> {


  //楼层数 默认1F
  String _floor = "1F";
  String _floorflg = "02";
  String _fnum = "1";
  BuildingIndexViewModel _viewModel;
  //编辑用到的企业信息
  FloorCompanyListBean _companyInfo;
  //上方需要保存的企业列表
  List<FloorCompanyListBean> _toSaveFloorList = new List();
  //下方已有的企业列表
  List<FloorCompanyListBean> _alreadyHaveFloorList = new List();
  ScrollController _scrollController;
  //用于记录最开始数据的json
  String _originJson = "";
  @override
  void initState() {
    super.initState();
    _scrollController = new ScrollController();
    _viewModel = new BuildingIndexViewModel(this);

    if(widget?.floorList != null && widget.floorList.length > 0){
      _alreadyHaveFloorList.addAll(widget.floorList);
    }
    if(StringUtils.isNotEmpty(widget?.floorName)){
      _floor = widget?.floorName;
    }else{
      //编辑
      _companyInfo = widget?.companyInfo;
      if(_companyInfo != null){
        //floorflg 01地下 02地上
        if("02" == _companyInfo.floorflg){
          _floor = _companyInfo.fnum + "F";
        }else{
          _floor = "B" + _companyInfo.fnum;
        }
      }
    }
    _floorflg = _floor?.contains("F")?"02":"01";
    _fnum = _floor?.replaceAll("F", "").replaceAll("B", "");
    _toSaveFloorList.add(new FloorCompanyListBean(floorflg: _floorflg, fnum: _fnum));
    _toSaveFloorList.add(new FloorCompanyListBean(floorflg: _floorflg, fnum: _fnum));

    List<FloorCompanyListBean> originFloorList = new List();
    if(_toSaveFloorList.isNotEmpty){
      _toSaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          originFloorList.add(element);
        }
      });
    }
    if(_alreadyHaveFloorList.isNotEmpty){
      _alreadyHaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          originFloorList.add(element);
        }
      });
    }

    _originJson = json.encode(originFloorList);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: WillPopScope(
          onWillPop: _withdrawFront,
          child: Scaffold(
            resizeToAvoidBottomInset: true,
            resizeToAvoidBottomPadding: true,
            backgroundColor: Color(0xFFF6F7F9),
            body: _toMainColumnWidget(),
          ),
        )
    );
  }

  ///获取修改后的json
  String getEditJson(){
    List<FloorCompanyListBean> toUploadFloorList = new List();
    if(_toSaveFloorList.isNotEmpty){
      _toSaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          toUploadFloorList.add(element);
        }
      });
    }
    if(_alreadyHaveFloorList.isNotEmpty){
      _alreadyHaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          toUploadFloorList.add(element);
        }
      });
    }
    return json.encode(toUploadFloorList);
  }

  void onBackPressed()async{
    String editJson = getEditJson();
    if((_originJson??"") == (editJson??"")){
      //直接返回
      RouterUtils.pop(context);
      return;
    }
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "您的操作尚未保存，是否放弃修改？",
        cancelText: "取消",
        confirmText: "放弃",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    //去裁剪
    if(result??false){
      RouterUtils.pop(context);
    }
  }

  Future<bool> _withdrawFront() async {
    String editJson = getEditJson();
    if((_originJson??"") == (editJson??"")){
      //直接返回
      return true;
    }
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "您的操作尚未保存，是否放弃修改？",
        cancelText: "取消",
        confirmText: "放弃",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    if(result??false){
      return true;
    }
    return false;
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        Expanded(
          child: ListView(
            shrinkWrap: true,
            padding: EdgeInsets.only(left:0, right:0, top:0, bottom: (_alreadyHaveFloorList.length != 0)?0:200),
            controller: _scrollController,
            children:[
              _toDefaultEmptyWidget(),
              // _toFilterWidget(),

              Visibility(
                visible: _alreadyHaveFloorList.length != 0,
                child: SizedBox(
                  height: 20,
                ),
              ),
              Visibility(
                visible: _alreadyHaveFloorList.length != 0,
                child: _toAlreadyHaveWidget(),
              ),
            ],
          ),
        ),

      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "楼层：${_floor??"1F"}",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightPadding: 15,
      rightWidget: _toSaveButtonWidget(),
      navFunction: (){
        onBackPressed();
      },
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 48,
      height: 24,
      unSelectBgColor:
      ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        _save();
      },
    );
  }

  //保存
  _save()async{
    bool needToast = false;
    if(_toSaveFloorList.isNotEmpty){
      _toSaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.hnum) && StringUtils.isEmpty(element.company)){
          needToast = true;
        }
      });
    }
    if(_alreadyHaveFloorList.isNotEmpty){
      _alreadyHaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.hnum) && StringUtils.isEmpty(element.company)){
          needToast = true;
        }
      });
    }

    if(needToast){
      bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "有企业信息未完善，确定保存",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        cancelBgColor: Color(0xFFF6F7F9),
        titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        widgetBgColor: Colors.white,
      );
      if(result??false){
        _saveFunction();
      }
    }else{
      _saveFunction();
    }

  }

  _saveFunction(){
    List<FloorCompanyListBean> toUploadFloorList = new List();
    if(_toSaveFloorList.isNotEmpty){
      _toSaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          toUploadFloorList.add(element);
        }
      });
    }
    if(_alreadyHaveFloorList.isNotEmpty){
      _alreadyHaveFloorList.forEach((element) {
        if(StringUtils.isNotEmpty(element.company)){
          toUploadFloorList.add(element);
        }
      });
    }

    String comJson = json.encode(toUploadFloorList);
    _viewModel.editCompanyByFloor(context, widget?.buildingIndexId, _fnum, _floorflg, comJson);
    print(_toSaveFloorList.length);
  }

  ///固定两行空布局
  Widget _toDefaultEmptyWidget(){
    return Column(
      children: [
        ListView.separated(
            padding: EdgeInsets.all(0),
            itemCount: (_toSaveFloorList?.length??0)+1,
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            itemBuilder: (BuildContext context, int index) {
              if(index < _toSaveFloorList.length){
                return _toSaveCompanyItemWidget(context, index, _toSaveFloorList[index]);
              }
              return _toAddCompanyWidget();

            },
            separatorBuilder: (BuildContext context, int index) {
              return _toFilterWidget();
            }),

      ],
    );
  }

  ///分割线
  Widget _toFilterWidget(){
    return Container(
      height: 1,
      color: Colors.white,
      child: Container(
        height: 1,
        color: Color(0XFFEEEEEE),
        margin: EdgeInsets.only(left: 15),
      ),
    );
  }

  ///添加企业
  Widget _toAddCompanyWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if((_toSaveFloorList.length + _alreadyHaveFloorList.length) >= 50){
          VgToastUtils.toast(context, "每层最多支持录入50个企业");
          return;
        }
        setState(() {
          _toSaveFloorList.add(new FloorCompanyListBean(floorflg: _floorflg, fnum: _fnum));
        });
      },
      child: Container(
        height: 50,
        color: Colors.white,
        padding: EdgeInsets.only(left: 15),
        alignment: Alignment.centerLeft,
        child: Row(
          children: [
            Image.asset(
              'images/icon_add_company.png',
              width: 17,
              height: 17,
            ),
            SizedBox(width: 4,),
            Text(
              "添加企业",
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
              ),
            )

          ],
        ),
      ),
    );
  }

  ///楼层公司列表item
  Widget _toSaveCompanyItemWidget(BuildContext context, int index, FloorCompanyListBean companyItem) {
    return FloorCompanyItemWidget(
      companyListBean: companyItem,
      onDelete: (item){
        setState(() {
          _toSaveFloorList.remove(item);
        });
      },
      resource: "login_close_ico",
    );
  }

  ///当前楼层已有企业
  Widget _toAlreadyHaveWidget(){
    return ListView.separated(
        padding: EdgeInsets.all(0),
        itemCount: _alreadyHaveFloorList?.length??0,
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return _toAlreadyHaveCompanyItemWidget(context, _alreadyHaveFloorList[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return _toFilterWidget();
        });
  }

  ///楼层公司列表item
  Widget _toAlreadyHaveCompanyItemWidget(BuildContext context, FloorCompanyListBean companyItem) {
    return FloorCompanyItemWidget(
      companyListBean: companyItem,
      onTapUp: (item, details){
        showAnimationDialog(
            context: context,
            transitionType: TransitionType.fade,
            barrierColor: Color(0x00000001),
            transitionDuration: Duration(milliseconds: 100),
            builder: (context) {
              return EditDeletePopMenuWidget(
                items: ["移除整条",],
                details: details,
                onClickItem: (content) async{
                  RouterUtils.pop(context);
                  if (content == "移除整条") {
                    setState(() {
                      _alreadyHaveFloorList.removeWhere((element) {
                        print("item:" + item.toJson().toString());
                        print("element:" + element.toJson().toString());
                        bool result = item.toJson().toString() == element.toJson().toString();
                        print("result:" + result.toString());
                        return result;
                      });
                    });
                  }
                },
              );
            }
        );
      },
      resource: "icon_edit_floor_company_info",
    );
  }

}
